var iframeCallbackFunction;
var iframeCallbackObject;
var ajajform_global_options={language: "en"};

function ajajform_set_global(k,v)
{
	ajajform_global_options[k]=v;
}

(function( $, undefined ) {
if ($.widget) {
/*
	\name ru Форма
	\save true
*/
$.widget("ui.ajajform", {
	options: {
		/* \type css */
		/* \description ru CSS-класс */
		cssclass: "ajajform",
		/* \type integer */
		/* \description ru Ширина описания по-умолчанию */
		labelwidth: 200,
		inputwidth: 200,
		/* \type text */
		/* \description ru Название формы по-умолчанию */
		name: "frm",
		// \type html
		// \name ru Расположение элементов внутри формы
		layouttemplate: '<div class="af-body"></div>',
		// \type array
		languages: [],
		readonly: false
	},
	//***********************************************************
	// Создаёт форму
	//***********************************************************
	_create: function() {
		var self=this;
		this.element.addClass(this.options.cssclass);
		var frm=document.createElement("form");
		this.element.append(frm);
		frm.onsubmit=function(e) {
			if (self.options.debug) console.log("ajajform.frm.onsubmit(): clicked");
			if (self.options.readonly) return false;
			if (self.allow_submit) return true;
			self.submitClicked(e);
			return false;
		};
		this.frm=frm;
		$("form",this.element).append(this.options.layouttemplate);
		this.refreshHeader();
		this.refreshSubmit();
		this.widgets={};
		this.iframeFrm=null;
	},
	//***********************************************************
	// Устанавливает значение и вызвывает refresh, если он есть
	//***********************************************************
	_setOption: function(key,value) {
		this.options[key]=value;
		var k1=key.substr(0,1);
		var k2=key.substr(1);
		var n="refresh"+k1.toUpperCase()+k2;
		if (this[n]) this[n]();
	},
	//***********************************************************
	// Обновляет заголовок формы
	//***********************************************************
	refreshHeader: function() {
		if (this.options.header!=null) {
			var a=$(".af-header",this.element);
			if (a.length) {
				a.text(this.options.header);
			} else {
				$(this.frm).prepend("<h1 class='af-header'>"+this.options.header+"</h1>");
			}
		} else {
			$(".af-header",this.element).remove();
		}
	},
	//***********************************************************
	// Вставляет widget
	//***********************************************************
	insertWidget: function(layoutDivId,beforeWidgetName,widgetOptions) {
		if (!layoutDivId) layoutDivId=widgetOptions.xpath||".af-body";
		var widgetName=widgetOptions.name;
		if (this.widgets[widgetName]) {
			console.log("Element exists "+widgetOptions.name+"/"+widgetOptions.type);
			return undefined;
		}
		var el;
		el=$(layoutDivId,this.element);
		if (el.length==0) console.log("No xpath element "+layoutDivId+" for element "+widgetOptions.name+"/"+widgetOptions.type);
		var t="ajajform_"+widgetOptions.type;
		var n=this.options.name+'-'+widgetName;
		this.widgets[widgetName]=t;
		if (this.options.readonly) widgetOptions.readonly=true;
		widgetOptions.tagid=n;
		return $("<div id='"+n+"'></div>").appendTo(el)[t](widgetOptions);
	},
	//***********************************************************
	// 
	//***********************************************************
	deleteWidget: function(widgetName) {
		if (!this.widgets[widgetName]) return;
		
		var n='#'+this.options.name+'-'+widgetName;
		var w=$(n,this.element);
		w[this.widgets[widgetName]]("destroy");
		w.remove();
		delete this.widgets[widgetName];
	},
	//***********************************************************
	// 
	//***********************************************************
	deleteWidgetsInLayoutBlock: function(layoutDivId) {
//		$("#debug").append("<div>deleteWidgetsInLayoutBlock</div>");
		for (var widgetName in this.widgets) {
			var n='#'+this.options.name+'-'+widgetName;
//			$("#debug").append("<div>n="+n+"</div>");
			if ($(layoutDivId+" "+n,this.element).length) this.deleteWidget(widgetName);
		}
	},
	//***********************************************************
	// Обновляет кнопки внизу, включая submit
	//***********************************************************
	refreshFooterButtons: function() {
		var arr=this.options.footerButtons?this.options.footerButtons.slice():new Array();
		if (this.options.submit && !this.options.readonly) arr.push(this.options.submit);
		if (arr.length==0) {$(".af-buttons",this.element).remove();return;}
		var a=$(".af-buttons",this.element);
		if (a.length==0) a=$('<div class="af-buttons"></div>').appendTo(this.frm).css("padding-left",this.options.labelwidth); else a.empty();
		for (var i=0;i<arr.length;i++) {
			var isSubmit=(i+1==arr.length && this.options.submit);
			var b=$(isSubmit?"<input type='button'/>":"<input type='button'/>").appendTo(a);
			b.prop("value",arr[i].value!=null?arr[i].value:"Submit");
//			b.text(arr[i].value!=null?arr[i].value:"Submit");
			b.button();
//			b.bind("click",{button: arr[i], t: this, func:isSubmit?"submitClicked":"buttonClicked"},function(e) { e.data.t[e.data.func](e,e.data.button); });
			if (isSubmit) {
				b.bind("click",{button: arr[i], t: this},function(e) { e.data.t.submitClicked(e,e.data.button); return false; });
//				b.bind("click",{t:this}, function(e) { $(e.data.t.frm).submit(); });
			} else {
				b.bind("click",{button: arr[i], t: this},function(e) { e.data.t.buttonClicked(e,e.data.button); });
			}
		}
	},
	//***********************************************************
	// Обвновляет submit
	//***********************************************************
	refreshSubmit: function() {
		this.refreshFooterButtons();
	},
	//***********************************************************
	// Проверяет значения всеъ элементов форм на валидность
	//***********************************************************
	validateForm: function() {
		var all=false;
		for (var widgetName in this.widgets) {
			var n='#'+this.options.name+'-'+widgetName;
			var w=$(n,this.element);
			var item=w[this.widgets[widgetName]]("validate");
			if (item) {
				if (this.options.debug) console.log("validate fails: "+n+" ("+this.widgets[widgetName]+")");
				all=true;
			}
		}
		return !all;
	},
	//***********************************************************
	// Обработка нажатия на submit
	//***********************************************************
	submitClicked: function(e) {
		if (this.options.debug) console.log("ajajform.submitClicked(): clicked");
		if (this.options.readonly) {
			if (this.options.debug) console.log("ajajform.submitClicked(): form is read-only");
			return false;
		}
		if (!this.validateForm()) {
			if (this.options.debug) console.log("ajajform.submitClicked(): validate fails");
			return false;
		}
		var r={};
		var r2={};
		if (this.options.submit.params) {
			for (var k in this.options.submit.params) r[k]=this.options.submit.params[k];
		}
		var isAjaj=this.options.submit.ajaj;
		for (var widgetName in this.widgets) {
			var n='#'+this.options.name+'-'+widgetName;
			var w=$(n,this.element);
			w[this.widgets[widgetName]]("postvalue",r,r2);
//			if (!isAjaj) w[this.widgets[widgetName]]("postvalueFile",r2);
		}
		if (this.options.submit.click) {
			if (!this.options.submit.click(r,r2)) {
				if (this.options.debug) console.log("ajajform.submitClicked(): this.options.submit.click() fails");
				return false;
			}
		}
		for (var tmp in r2) isAjaj=false;
		if (r2.length) isAjaj=false;
		for (var k in r) if (r[k]==null || r[k]==undefined) r[k]="";
		if (isAjaj) {
			if (this.options.debug) console.log("ajajform.submitClicked(): submitting via ajax");
			this.submitResponse(
				$.ajax({
					type: "POST",
					url: this.options.submit.url,
					data: r,
					async: false
				}).responseText
			);
		} else {
			if (this.options.debug) console.log("ajajform.submitClicked(): sending to iframe");
			this.mkIframeForm();
			var frm=$("form",this.element);
			$("input",frm).not(".fileInput").prop("disabled",true);
			$("select",frm).prop("disabled",true);
			$("textarea",frm).prop("disabled",true);
			$(".autoAdded",frm).remove();
			this.fillObjectToForm(frm,r,false);
//			this.fillObjectToForm(frm,r2,true); Input objects must already be
			this.addInput(frm,"hidden","is-iframe","1");
			frm.prop("target",this.options.name+'-iframe');
			frm.prop("action",this.options.submit.url);
			frm.prop("method","POST");
			frm.prop("enctype","multipart/form-data");
			this.allow_submit=true;
			frm.submit();
			iframeCallbackFunction="submitResponse";
			iframeCallbackObject=this;
		}
		return false;
	},
	//***********************************************************
	//
	//***********************************************************
	submitResponse: function(rtext) {
		std_response(rtext);
	},
	//***********************************************************
	// Возращает widgets
	//***********************************************************
	getWidgets: function(widgetName) {
		return this.widgets;
	},
	//***********************************************************
	// Возращает widget
	//***********************************************************
	getWidget: function(widgetName) {
		var n='#'+this.options.name+'-'+widgetName;
		var w=$(n,this.element);
		return w;
//		return w[this.widgets[widgetName]];
	},
	//***********************************************************
	// Возращает значение элемента
	//***********************************************************
	getWidgetValue: function(widgetName) {
		var r={};
		var n='#'+this.options.name+'-'+widgetName;
		var w=$(n,this.element);
		w[this.widgets[widgetName]]("postvalue",r);
		return r[widgetName];
	},
	//***********************************************************
	// Сохраняет значение в элемент
	//***********************************************************
	setWidgetOption: function(widgetName,k,r) {
		var n='#'+this.options.name+'-'+widgetName;
		var w=$(n,this.element);
		w[this.widgets[widgetName]]("option",k,r);
	},	
	//***********************************************************
	// Сохраняет значение в элемент
	//***********************************************************
	setWidgetValue: function(widgetName,r) {
		var n='#'+this.options.name+'-'+widgetName;
		var w=$(n,this.element);
		if (w.length==0) return;
		w[this.widgets[widgetName]]("option","value",r);
		w[this.widgets[widgetName]]("validate");
	},
	//***********************************************************
	// Сохраняет элементы объекта в <form>, используется
	// при вызове через iframe
	//***********************************************************
	fillObjectToForm: function(form,obj,isFile) {
		var t=isFile?"file":"hidden";
		for (var k in obj) {
			var v=obj[k];
			if (v==undefined) {
				this.addInput(form,t,k,"");
			} else if (v==null) {
				this.addInput(form,t,k,"");
			} else if (v.constructor==Array) {
				for (var i=0;i<v.length;i++) this.addInput(form,t,k,v[i]);
			} else {
				this.addInput(form,t,k,v);
			}
		}
	},
	//***********************************************************
	// Добавляет <input>, используется из fillObjectToForm
	//***********************************************************
	addInput: function(form,type,k,v) {
		if (type=="file") {
			$('<input class="autoAdded" type="'+type+'" name="'+k+'"value="'+v+'"/>').appendTo(form);
		} else {
			$('<input class="autoAdded" type="'+type+'"/>').appendTo(form).prop("name",k).val(v);
		}
	},	
	//***********************************************************
	// Обработка нажатия на кнопку
	//***********************************************************
	buttonClicked: function(e,button) {
		if (button.click) {
			if (!button.click()) return;
		}
		if (button.url) {
			document.location=button.url;
		}
	},
	//***********************************************************
	// 
	//***********************************************************
	getSubmitParam: function(p) {
		return this.options.submit.params[p];
	},
	//***********************************************************
	// 
	//***********************************************************
	setSubmitParam: function(p,v) {
		return this.options.submit.params[p]=v;
	},
	//***********************************************************
	// 
	//***********************************************************
	destroy: function() {
	},
	//***********************************************************
	// 
	//***********************************************************
	mkIframeForm: function() {
		if (this.iframe) return;
		var iframe=$('<iframe name="'+this.options.name+'-iframe" id="'+this.options.name+'-iframe" frameborder="0"></iframe>').appendTo(this.element);
//		this.iframeForm=$('<form name="'+this.options.name+'-iframe-form"></form>').appendTo(this.element);
//		this.addInput(this.iframeForm,'hidden','is-iframe','1');
	}
	//***********************************************************
	// 
	//***********************************************************
});
}
})( jQuery );

function ajajform_frm_set_id(data)
{
	frm.ajajform("setSubmitParam",data.name,data.id);
}

